package com.kvn.universal.filter.lock;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis缓存服务提供者，实质是对jedisPool的包装
 * 
 */
public final class RedisProvider {
	private static String redisHost;
	private static int redisPort;
	private static int maxIdle;
	private static int maxTotal;
	private static long maxWaitMillis;
	private static boolean testOnBorrow;
	private static int database;

	private static JedisPool pool;

	public static void init() {
		if(pool != null){
			return;
		}

		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(maxIdle);
		config.setMaxTotal(maxTotal);
		config.setMaxWaitMillis(maxWaitMillis);
		config.setTestOnBorrow(testOnBorrow);
		pool = new JedisPool(config, redisHost, redisPort, 15000, null, database, null);
	}

	/**
	 * 重新加载配置，用于配置文件改变时刷新缓冲池配置 使用此方式，如果无法读取配置，也会使用默认配置，强制创建一个pool，慎用。
	 *
	 * @return
	 */
	public static synchronized void refresh() {
		destroy();
		init();
	}

	/**
	 * 获取redis客户端
	 */
	public static Jedis getClient() {
		Jedis jedis;
		if (pool != null) {
			jedis = pool.getResource(); // 如已经创建则立即返回
		} else {
			synchronized (RedisProvider.class) {
				if (pool == null) { // 其他线程如创建，则跳过
					refresh();
				}
			}
			jedis = pool.getResource();
		}

		return jedis;
	}

	public static void destroy() {
		if (pool != null) {
			pool.destroy();
		}
	}

	public void setRedisHost(String redisHost) {
		RedisProvider.redisHost = redisHost;
	}

	public void setRedisPort(int redisPort) {
		RedisProvider.redisPort = redisPort;
	}

	public void setMaxIdle(int maxIdle) {
		RedisProvider.maxIdle = maxIdle;
	}

	public void setMaxTotal(int maxTotal) {
		RedisProvider.maxTotal = maxTotal;
	}

	public void setMaxWaitMillis(long maxWaitMillis) {
		RedisProvider.maxWaitMillis = maxWaitMillis;
	}

	public void setTestOnBorrow(boolean testOnBorrow) {
		RedisProvider.testOnBorrow = testOnBorrow;
	}

	public void setDatabase(int database) {
		RedisProvider.database = database;
	}

}
